// 账户信息
import { defineStore } from 'pinia'
import { local } from '../util/storage'

const state = () => ({
  accessToken: local({ key: 'ACCESS_TOKEN' }) || '',
  refreshToken: local({ key: 'REFRESH_TOKEN' }) || '',
  expireTime: local({ key: 'EXPIRE_TIME' }) || 0,

  user: local({ key: 'USER' }) || { username: '系统管理员' },

  routers: local({ key: 'ROUTERS' }) || [],
  permissions: local({ key: 'PERMISSIONS' }) || [],

  // openid: local({ key: 'OPENID' }) || '',
})

const getters = {}

const actions = {
  // 设置 State
  setState({ key, value }: { key: S; value: any }) {
    this[key] = value
  },

  // 设置菜单
  setMenu(data: any) {
    const routers = data?.data?.routes || []
    const permissions = data?.data?.permissions || []

    local({ key: 'ROUTERS', value: routers })
    local({ key: 'PERMISSIONS', value: permissions })
    this.routers = routers
    this.permissions = permissions
  },

  // 设置用户信息
  setUser(data: any) {
    const user = data.principal
    local({ key: 'USER', value: user })
    this.user = user
  },

  // 登录
  login(data: any) {
    const { access_token, refresh_token, expires_in } = data
    const current = new Date()
    const expireTime = current.setTime(current.getTime() + expires_in * 1000)

    local({ key: 'ACCESS_TOKEN', value: access_token })
    local({ key: 'REFRESH_TOKEN', value: refresh_token })
    local({ key: 'EXPIRE_TIME', value: expireTime })
    this.accessToken = access_token
    this.refreshToken = refresh_token
    this.expireTime = expireTime
  },

  // 注销
  logout() {
    this.accessToken = ''
    this.refreshToken = ''
    this.expireTime = ''
    this.user = {}
    this.routes = []
    this.permissions = []

    // local({ clear: true })
    local({ key: 'ACCESS_TOKEN', remove: true })
    local({ key: 'REFRESH_TOKEN', remove: true })
    local({ key: 'EXPIRE_TIME', remove: true })
    local({ key: 'USER', remove: true })
    local({ key: 'ROUTERS', remove: true })
    local({ key: 'PERMISSIONS', remove: true })
  },
}

export const useStore = (id: S) =>
  defineStore({ id, state, getters, actions })()
